const fs = require('fs')
const path = require('path')

// 获取参数
const args = process.argv.splice(2)
const command = args.shift()
const taskDescription = args.join(' ')

const file = path.join(process.cwd(), '/.tasks')

const loadOrInitializeTaskArray = (file) => {
  if (!fs.existsSync(file)) {
    return []
  }
  const data = fs.readFileSync(file, {encoding: 'utf-8'})
  return JSON.parse(data)
}

const storeTasks = (file, tasks) => {
  fs.writeFileSync(file, JSON.stringify(tasks), {encoding: 'utf-8'})
}

const listTask = (file) => {
  const tasks = loadOrInitializeTaskArray(file)
  if (!tasks.length) {
    console.log('No tasks.')
    return
  }
  tasks.forEach(item => {
    console.log(item)
  })
}

const addTask = (file, taskDescription) => {
  const tasks = loadOrInitializeTaskArray(file)
  tasks.push(taskDescription)
  storeTasks(file, tasks)
  console.log('Saved.')
}

switch (command) {
  case 'list':
    listTask(file)
    break
  case 'add':
    addTask(file, taskDescription)
    break
  default:
    console.log(`Usage: list|add [taskDescription]`)
}
